/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_orm.htm
 *
 * Zhiqim Orm is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.orm.executor;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.zhiqim.kernel.model.maps.MapSS;
import org.zhiqim.kernel.model.objects.SO;
import org.zhiqim.kernel.util.Closes;
import org.zhiqim.kernel.util.Sqls;
import org.zhiqim.orm.ORMException;
import org.zhiqim.orm.ORMServer;
import org.zhiqim.orm.datasource.ZResultSet;
import org.zhiqim.orm.datasource.ZStatement;
import org.zhiqim.orm.dbo.Dbo;
import org.zhiqim.orm.exception.TableNotExistException;

/**
 * 查询处理器接口，参数为Class类型[org.zhiqim.dbo.User]，结果集为MapSO类型
 * 
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class QueryExecutorClassMap implements QueryExecutor
{
    /**
     * 执行executeQuery处理
     * 
     * @param server        ORM服务
     * @param conn          数据库连接
     * @param sql           ZSQL语句
     * @param param         参数
     * @param replaceMap    可替换表
     * @return              返回结果集列表
     * @throws ORMException 映射异常
     */
    public List<?> execute(ORMServer server, Connection conn, String sql, Class<?> resultClass, Object param, MapSS replaceMap) throws ORMException
    {
        PreparedStatement pstmt = null;
        ResultSet rst = null;
        String str = null;

        try
        {
            // 1.替换可替换符$$
            sql = Sqls.formatReplaceMap(sql, replaceMap);

            Dbo paramDbo = server.getDbo(param.getClass());

            // 获取通配符##
            List<SO> paramKeyList = new ArrayList<>();
            for (int i = 0, start = 0, end = sql.indexOf('#'); end != -1; i++, start = end, end = sql.indexOf('#', start + 1))
            {
                if (i % 2 == 0)
                    continue;
                
                String paramKey = sql.substring(start + 1, end);// 取出KEY,支持类field和表column
                String method = paramDbo.getGetMethod(paramKey);
                if (method == null)
                    throw new ORMException("_Table/_View/_Dbo[" + paramDbo.getClass().getName() + "]没有找到" + paramKey + "对应的方法]");

                // 反射机制取值
                Method m = param.getClass().getMethod(method, new Class[0]);
                Object value = m.invoke(param, new Object[0]);
                paramKeyList.add(new SO(paramKey, value));
            }

            // 把SQL中通配符改成?
            for (int i=0;i<paramKeyList.size();i++)
            {
                String paramKey = paramKeyList.get(i).key();
                sql = sql.replaceAll("#" + paramKey + "#", "?");// 把#paramKey#换成?
            }

            // SQL语句处理完毕
            if (server.isQuerySqlLog())
                str = sql;

            pstmt = conn.prepareStatement(sql);
            for (int i=0;i<paramKeyList.size();i++)
            {
                Object value = paramKeyList.get(i).value();
                if (server.isQuerySqlLog())
                    str = ZStatement.setParameter(server, pstmt, i + 1, value, str);
                else
                    ZStatement.setParameter(server, pstmt, i + 1, value);
            }

            // 查询可以打印SQL
            if (server.isQuerySqlLog())
            {
                str = str.replaceAll("-%6-%-3%-", "?");
                qSqlLog.info(str);
            }

            rst = pstmt.executeQuery();
            
            //解决结果集到哈唏表中
            return ZResultSet.parseToMap(rst, resultClass);
        }
        catch (SQLException e) 
        {
            if (server.getPolicy().isTableNotExist(e))
                throw new TableNotExistException("[%s][%s]", e, e.getMessage(), sql);
            else
                throw new ORMException("[%s][%s]", e, e.getMessage(), sql);
        }
        catch (Throwable e)
        {
            throw new ORMException("[%s][%s]", e, e.getMessage(), sql);
        }
        finally
        {
            Closes.closeIgnoreException(rst, pstmt);
        }
    }
}
